/**
 * 
 */
package net.phoenix.repository.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author lixf
 *
 */
public class JdbcDaoFactory {
	private Map<Class<? extends JdbcDao>, Class<? extends JdbcDao>> mapping;

	public JdbcDaoFactory(){
		this.mapping = new HashMap<Class<? extends JdbcDao>, Class<? extends JdbcDao>>();
	}

	public void loadMappingFromClassPath(String name) throws IOException {
		InputStream is = this.getClass().getClassLoader().getResourceAsStream(name);
		this.loadMapping(is);
		is.close();
	}

	public void loadMapping(InputStream is) throws IOException {
		Properties data = new Properties();
		data.load(is);
		for (Object key : data.keySet()) {
			String value = data.get(key).toString();
			try {
				this.mapping
						.put(Class.forName(key.toString())
								.asSubclass(JdbcDao.class), 
								Class.forName(value).asSubclass(JdbcDao.class));
			} catch (ClassNotFoundException ex) {
				throw new JdbcException(ex);
			}
		}
	}

	/**
	 * 获取一个DAO实现
	 * 
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T extends JdbcDao> T getJdbcDao(Class<T> clazz, Connection connection) {
		Class<? extends JdbcDao> implClass = this.mapping.get(clazz);
		try {
			JdbcDao dao = implClass.newInstance();
			dao.setConnection(connection);
			return (T) dao;
		} catch (Exception e) {
			throw new JdbcException(e);
		}
	}

}
